import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ButtonBarSimilar extends StatefulWidget {
  ButtonBarSimilar({Key key}) : super(key: key);

  @override
  _ButtonBarSimilarState createState() => _ButtonBarSimilarState();
}

class _ButtonBarSimilarState extends State<ButtonBarSimilar> {
  int selectNum = 10;
  Widget _getButtonItem(text) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selectNum = text;
        });
      },
      child: Container(
          margin: EdgeInsets.only(bottom: 10),
          decoration: BoxDecoration(
              border: Border.all(
                  color: text == selectNum ? Colors.blue : Colors.grey),
              borderRadius: BorderRadius.all(Radius.circular(5))),
          alignment: Alignment.center,
          height: 60,
          child: Text('$text元')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        SimilarButtonBar(
          children: <Widget>[
            _getButtonItem(10),
            _getButtonItem(20),
            _getButtonItem(50),
          ],
        ),
        SimilarButtonBar(
          children: <Widget>[
            _getButtonItem(100),
            _getButtonItem(200),
            _getButtonItem(500),
          ],
        ),
      ],
    ));
  }
}

class SimilarButtonBar extends StatelessWidget {
  SimilarButtonBar({Key key, this.children, this.spacing: 10, this.rowCount})
      : super(key: key);

  final List<Widget> children;

  /// 间隔
  final double spacing;

  /// 每一行的个数
  final int rowCount;

  List<Widget> _getItem(child, isLast) {
    List<Widget> list = [Expanded(flex: 1, child: child)];
    if (!isLast) {
      list.add(SizedBox(
        width: spacing,
      ));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    int length = children.length;
    List<Widget> list = [];
    children.forEach((child) {
      list.addAll(_getItem(child, child == children[length - 1]));
    });
    return Flex(direction: Axis.horizontal, children: list);
  }
}
